package datastructure.queue;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-18
 */
public class CycleArrayQueueDemo {

}

/**
 * 使用数组来实现队列
 */
class CycleArrayQueue {
    // 队列最大容量
    private int maxSize = 1024;
    // 指向队列头部
    private int front;
    // 指向队列尾部
    private int rear;
    // 使用数组充当队列
    private int[] array;

    public CycleArrayQueue() {
        new ArrayQueue(maxSize);
    }

    public CycleArrayQueue(int maxSize) {
        if (maxSize < 0) {
            throw new RuntimeException("队列容量不能小于0");
        }
        if (maxSize > this.maxSize) {
            array = new int[this.maxSize];
        } else {
            array = new int[maxSize];
        }
    }

    /**
     * 判断队列是否已满
     */
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    /**
     * 判断队列是否为空
     */
    public boolean isEmpty() {
        return front == rear;
    }

    /**
     * 添加数据
     */
    public void add(int n) {
        if (isFull()) {
            throw new RuntimeException("队列已满");
        }

        array[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    /**
     * 获取数据
     */
    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列没有数据");
        }
        int value = array[front];
        front = (front + 1) % maxSize;
        return value;
    }

    /**
     * 显示队列数据
     */
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列没有数据");
            return;
        }
        for (int i = front; i < front + size(); i++) {
            System.out.println(array[i % maxSize]);
        }
    }

    /**
     * 返回有效数个数
     */
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    /**
     * 获取队列头部数据
     */
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("队列没有数据");
        }
        return array[front];
    }
}